<template>
  <div class="page network-setting">
    <div class="scroll-view">
      <customHeader :middleTitle="headerTitle" @leftCallBack="goBack"/>
      <awesome-picker
        ref="wifiPicker"
        :textTitle="wifiPicker.textTitle"
        colorTitle="#38ADFF"
        colorConfirm="#38ADFF"
        :data="wifiPicker.data"
        :anchor="wifiPicker.anchor"
        @confirm="handlePickerConfirm"
        v-if="hasWiFiList"
      ></awesome-picker>
      <div class="top-tip" v-if="type==18">提示：暂不支持5G频道Wi-Fi配置</div>
      <div class="page-body">
        <div :class="{positionHide:broadcast||qrCodeVisible}">
          <div class="top">
            <i class="zhk-ljwl"></i>
            <div>配置设备的连网Wi-Fi</div>
          </div>
          <ul class="ul-list">
            <li v-show="!hasWiFiList">
              <span>正在获取…</span>
            </li>
            <li v-show="hasWiFiList" @click="showPicker('wifiPicker')">
              <span>{{this.wifiPicker.selected.text}}</span>
              <div>
                <i class="zhk-list_rarrow down"></i>
              </div>
            </li>

            <li v-show="wifiPicker.selected.text==='自定义'">
              <div>
                <inputClear placeholder="请输入Wi-Fi名称" v-model="wifiName"/>
              </div>
            </li>
            <li>
              <div>
                <inputClear
                  placeholder="请输入Wi-Fi密码"
                  v-model="wifiPassword"
                  :max="64"
                  :maxlength="64"
                />
              </div>
            </li>
          </ul>
          <div class="btn-wrap">
            <div class="btn" :class="{disabled:passwordNotPass}" @click="submit">下一步</div>
          </div>
          <div class="tip-wrap" v-if="type==18">
            <div class="tip">
              <p>安卓手机获取不到附近Wi-Fi?</p>
              <p>1、打开GPS功能；</p>
              <p>2、手机给APP获取定位的权限；</p>
            </div>
          </div>
        </div>
        <div class="broadcast" :class="{positionHide:!broadcast}">
          <div class="bg">
            <ul class="circles">
              <li></li>
              <li></li>
              <li></li>
            </ul>
            <div class="pic"></div>
          </div>
          <div class="title">正在发送配置数据</div>
          <div class="content">预计共需90秒</div>
          <div class="tip">
            <p>• 请确认手机在设备附近5米之内</p>
            <p>• 请确认设备已开机</p>
          </div>
        </div>
        <div class="qrCode" :class="{positionHide:!qrCodeVisible}">
          <div class="qr-top">
            <div class="title">请使用设备扫描屏幕二维码</div>
            <div class="code-wrap">
              <qr-code :text="encode" :size="186"></qr-code>
            </div>
          </div>
          <div class="btn-wrap" @click="goBack">
            <div class="btn">关闭</div>
          </div>
          <div class="help-tips">
            帮助：请使用快小盒设备扫描手机屏幕二维码配置Wi-Fi
          </div>
          <div class="img-wrap">
            <img :src="require('../../../static/images/kxh_ad.gif')" alt="">
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import customHeader from "../../components/header/header";
import inputClear from "../../components/inputClear/inputClear";
import { Toast, MessageBox } from "mint-ui";
import jsBridge from "../../tools/jsBridge.js";
import AwesomePicker from "vue-awesome-picker";
Vue.use(AwesomePicker);
import VueQRCodeComponent from 'vue-qrcode-component'
Vue.component('qr-code', VueQRCodeComponent)
export default {
  name: "networkSetting",
  data() {
    return {
      online: false,
      sn: "",
      type: "",
      shopId: "",
      second: 90,
      broadcast: false, //发广播配置中（码卡龙）
      qrCodeVisible: false,//是否显示配网二维码（快小盒）
      hasWiFiList: false,
      wifiName: "",
      wifiPassword: "",
      wifiPicker: {
        anchor: [],
        textTitle: "",
        selected: { text: "" },
        data: []
      },
      encode: ""
    };
  },
  methods: {
    goBack() {
      if (this.broadcast) {
        MessageBox({
          title: "提示",
          message: "返回后将中断配网，确定要返回吗？",
          showCancelButton: true,
          closeOnClickModal: false
        }).then(action => {
          if (action === "confirm") {
            window.clearInterval(this.timer);
            this.broadcast = false;
            this.second = 90;
            jsBridge.stopBroadcast(function (result) {

            });
          }
        });
      } else if (this.qrCodeVisible) {
        this.$router.push({ path: "/qrCodeSound/mainSettings", query: { sn: this.sn, type: this.type, shopId: this.shopId } });
      }
      else {
        if (String(this.$route.query.close) == "true") {
          jsBridge.closeWindow();
        } else {
          this.$router.back();
        }
      }
    },
    showPicker(ref) {
      this.$refs[ref].show();
    },
    handlePickerConfirm(v) {
      this.wifiPicker.selected.text = v[0].value;
      this.wifiName = "";
      this.wifiPassword = "";
    },
    //快小盒生成配网二维码；码卡龙离线通过手机发送广播wifi数据，在线通过接口下发wifi数据
    submit() {
      if (this.passwordNotPass) {
        return;
      }
      if (this.wifiPicker.selected.text === "自定义" && !this.wifiName) {
        Toast("请输入Wi-Fi名称");
        return;
      }
      if (this.wifiPicker.selected.text !== "自定义") {
        this.wifiName = this.wifiPicker.selected.text;
      }
      //快小盒配网
      if (this.type == 20||this.type == 32||this.type == 38) {
        this.encode = `P:${this.wifiPassword};S:${this.wifiName};`;
        this.qrCodeVisible = true;
        return;
      }

      //设备在线，则通过调用接口修改密码
      if (this.online === true) {
        this.updateWiFi();
        return;
      }
      const _this = this;
      jsBridge.startBroadcast(
        {
          type: "setUpNetwork",
          content:
            '{"name":"' +
            _this.wifiName +
            '","password":"' +
            _this.wifiPassword +
            '"}'
        },
        function (result) {

        }
      );
      this.broadcast = true;
      this.second = 90;

      this.countDownReq();
    },

    //获取WiFi列表
    getWiFiList() {
      const _this = this;
      this.wifiPicker.data = [];
      _this.hasWiFiList = false;
      jsBridge.getNearByWIFI(function (result) {
        if (result["resultObject"]) {
          for (let item of result.resultObject) {
            _this.wifiPicker.data.push({ value: item });
          }
        }
        _this.wifiPicker.data.push({ value: "自定义" });
        _this.hasWiFiList = true;
        _this.wifiPicker.selected.text =
          result["resultObject"] && result["resultObject"][0]
            ? result["resultObject"][0]
            : "自定义";
        _this.$forceUpdate();
      });
      // setTimeout(() => {
      //   const result = ["YunZong"];
      //   for (let item of result) {
      //     _this.wifiPicker.data.push({ value: item });
      //   }
      //   _this.wifiPicker.data.push({ value: "自定义" });
      //   _this.hasWiFiList = true;
      //   _this.wifiPicker.selected.text = result && result[0];
      // }, 2000);
    },
    //获取设备是否连网成功(flg:1第一次查询 -1最后一次查询)
    getDeviceInfo(flg) {
      const url = `app/voice/queryWifiStatus.do?sn=${this.sn}`;
      this.ajax({
        url: url,
        type: "get",
        controlLoading: false
      })
        .then(res => {
          if (res.resultObject == true) {
            window.clearInterval(this.timer); //停止查询连网请求
            //停止广播
            jsBridge.stopBroadcast(function (result) {

            });

            MessageBox({
              title: "",
              confirmButtonText: "完成",
              message: "设备连网成功",
              showCancelButton: false,
              closeOnClickModal: false
            }).then(action => {
              if (action == "confirm") {
                //请求扫码接口
                this.findDeviceInfo(this.sn);
              }
            });
          } else {
            if (flg === -1) {
              MessageBox({
                title: "网络连接超时",
                message:
                  "<p style='text-align:left'>• 请确认手机在设备附近5米之内<br />• 请确认设备已开机</p>",
                confirmButtonText: "返回重试",
                showCancelButton: false,
                closeOnClickModal: false
              }).then(action => {
                if (action == "confirm") {
                  this.broadcast = false;
                }
              });
            }
          }
        })
        .catch(err => {

        });
    },
    //修改wifi
    updateWiFi() {
      const url = `app/voice/updateWifi.do?sn=${this.sn}&wifiName=${
        this.wifiName
        }&wifiPwd=${this.wifiPassword}`;
      this.ajax({
        url: url,
        type: "get",
        controlLoading: false
      })
        .then(res => {
          if (res.success == true) {
            MessageBox({
              title: "",
              confirmButtonText: "完成",
              message: "提交成功",
              showCancelButton: false,
              closeOnClickModal: false
            }).then(action => {
              if (action == "confirm") {
                //请求扫码接口
                this.findDeviceInfo(this.sn);
              }
            });
          } else {
            MessageBox({
              title: "",
              message: res.msg,
              confirmButtonText: "知道了",
              showCancelButton: false,
              closeOnClickModal: false
            });
          }
        })
        .catch(err => {

        });
    },
    //根据倒计时剩余时间调整请求频率
    countDownReq() {
      this.timer = window.setInterval(() => {
        this.second--;
        if (this.second <= 0) {
          jsBridge.stopBroadcast(function (result) {

          });
          this.getDeviceInfo(-1);
          window.clearInterval(this.timer);
          // } else if (
          //   this.second <= 70 &&
          //   this.second > 40 &&
          //   this.second % 10 === 0
          // ) {
          //   this.getDeviceInfo();
          // } else if (
          //   this.second <= 40 &&
          //   this.second > 1 &&
          //   this.second % 5 === 0
          // ) {
        } else if (
          this.second <= 90 &&
          this.second > 1 &&
          this.second % 5 === 0
        ) {
          this.getDeviceInfo();
        }
      }, 1000);
    },
    //判断是否跳绑定门店或者开通进件
    findDeviceInfo(sn) {
      const url = `app/voice/findDeviceInfo.do?sn=${sn}`;
      this.ajax({
        url: url,
        type: "get",
        controlLoading: true
      })
        .then(result => {
          if (result.success) {
            const res = result.resultObject;
            if (res.action == 2) {
              //绑定门店
              sessionStorageClient.putJSON("deviceStoreList", res.shopLists); //将门店列表存储，绑定门店页面使用
              this.$router.push({
                path: "/qrCodeSound/bindingStore",
                query: {
                  sn: res.sn,
                  type: res.type,
                  close: "true"
                }
              });
            } else if (res.action == 3) {
              //开通进件
              this.$router.push({
                path: "/qrCodeSound/authNone",
                query: {
                  className: "mkl-unopen",
                  shopId: res.shopId,
                  sn: res.sn,
                  type: res.type,
                  close: "true"
                }
              });
            } else if (res.action == 4) {
              //主设置面板
              const data = res["data"];
              this.$router.push({
                path: "/qrCodeSound/mainSettings",
                query: {
                  sn: data.sn,
                  type: data.type,
                  shopId: data.shopId,
                  close: "true"
                }
              });
            } else if (res.action == 5) {
              //扫进件二维码（状态为进件中 跳转到门店管理页面）
              this.$router.push({
                path: "/storeManage"
              });
            }
          } else if (result.code == -2) {
            //没有权限
            MessageBox({
              title: "",
              message: "没有权限",
              showCancelButton: false,
              confirmButtonText: "知道了",
              closeOnClickModal: false
            }).then(action => {
              if (action == "confirm") {
                jsBridge.closeWindow();
              }
            });
          } else {
            MessageBox({
              title: "",
              message: result.msg,
              showCancelButton: false,
              confirmButtonText: "知道了",
              closeOnClickModal: false
            }).then(action => {
              if (action == "confirm") {
                jsBridge.closeWindow();
              }
            });
          }
        })
        .catch(err => {

        });
    },

    //app再次唤醒，调用获取wifi列表接口
    bindResumeEvent() {
      const self = this;
      jsBridge.addResumeEventListener(() => {
        self.getWiFiList();
      });
    }
  },
  computed: {
    headerTitle() {
      return window.CommonUtil.getMachineNameByType(this.type);
    },
    passwordNotPass() {
      if (this.hasWiFiList) {
        const len = this.wifiPassword.length;
        if (len != 0 && (len < 8 || len >= 64)) {
          return true;
        } else {
          return false;
        }
      } else {
        return true;
      }
    }
  },
  created() {
    this.sn = this.$route.query.sn;
    this.type = this.$route.query.type;
    this.shopId = this.$route.query.shopId;
    this.online = this.$route.query.online;
  },
  mounted() {
    this.getWiFiList();
    this.bindResumeEvent();
  },
  components: {
    customHeader,
    inputClear
  }
};
</script>
<style lang="scss" scoped>
@import "qrCodeSound";
</style>
